//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.farm.doc.server.impl;

import com.farm.core.auth.domain.LoginUser;
import com.farm.core.sql.query.DBRule;
import com.farm.core.time.TimeTool;
import com.farm.doc.dao.DocfiletextDaoInter;
import com.farm.doc.dao.FarmDocfileDaoInter;
import com.farm.doc.dao.FarmRfDoctextfileDaoInter;
import com.farm.doc.domain.Docfiletext;
import com.farm.doc.domain.FarmDocfile;
import com.farm.doc.domain.FarmRfDoctextfile;
import com.farm.doc.server.FarmFileManagerInter;
import com.farm.doc.server.FarmFileManagerInter.FILE_TYPE;
import com.farm.doc.server.commons.DocumentConfig;
import com.farm.doc.server.commons.FarmDocFiles;
import com.farm.parameter.FarmParameterService;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class FarmFileManagerImpl implements FarmFileManagerInter {
	@Resource
	private FarmDocfileDaoInter farmDocfileDao;
	@Resource
	private DocfiletextDaoInter docfiletextDaoImpl;
	@Resource
	private FarmRfDoctextfileDaoInter farmRfDoctextfileDao;
	private static final Logger log = Logger.getLogger(FarmFileManagerImpl.class);
	private static final Map<String, FarmDocfile> fileCatch = new HashMap();

	public FarmFileManagerImpl() {
	}

	@Transactional
	public String saveFile(File file, FILE_TYPE type, String title, LoginUser user) {
		String exName = FarmDocFiles.getExName(title);
		if (exName.trim().toUpperCase().replace(".", "").equals("ZIP")) {
			type = FILE_TYPE.RESOURCE_ZIP;
		}

		if (".JPG .JPEG .GIF .PNG .BMP".indexOf(exName.trim().toUpperCase().replace(".", "")) >= 0) {
			type = FILE_TYPE.RESOURCE_IMG;
		}

		String userId = null;
		String userName = null;
		if (user != null && user.getName() != null) {
			userId = user.getId();
			userName = user.getName();
		} else {
			userId = "none";
			userName = "none";
		}

		file = FarmDocFiles.renameFile(file, UUID.randomUUID().toString().replaceAll("-", "") + exName + ".file");
		FarmDocfile docfile = new FarmDocfile(FarmDocFiles.generateDir(),
				UUID.randomUUID().toString().replaceAll("-", ""), type.getValue(), title, file.getName(),
				TimeTool.getTimeDate14(), TimeTool.getTimeDate14(), userName, userId, userName, userId, "0",
				(String) null, exName, Float.valueOf(String.valueOf(file.length())));
		if (user == null || user.getName() == null) {
			docfile.setCusername("none");
			docfile.setEusername("none");
		}

		FarmDocFiles.copyFile(file, FarmDocFiles.getFileDirPath() + docfile.getDir());
		docfile = this.farmDocfileDao.insertEntity(docfile);
		return docfile.getId();
	}

	@Transactional
	public String saveFile(InputStream inStream, String filename, String title, FILE_TYPE type, LoginUser user) {
		String exName = FarmDocFiles.getExName(title);
		filename = UUID.randomUUID().toString().replaceAll("-", "") + exName + ".file";
		if (exName.trim().toUpperCase().replace(".", "").equals("ZIP")) {
			type = FILE_TYPE.RESOURCE_ZIP;
		}

		String userId = null;
		String userName = null;
		if (user != null && user.getName() != null) {
			userId = user.getId();
			userName = user.getName();
		} else {
			userId = "none";
			userName = "none";
		}

		FarmDocfile docfile = new FarmDocfile(FarmDocFiles.generateDir(),
				UUID.randomUUID().toString().replaceAll("-", ""), type.getValue(), title, filename,
				TimeTool.getTimeDate14(), TimeTool.getTimeDate14(), userName, userId, userName, userId, "0",
				(String) null, exName, Float.valueOf(String.valueOf(0)));
		if (user == null || user.getName() == null) {
			docfile.setCusername("none");
			docfile.setEusername("none");
		}

		long length = FarmDocFiles.saveFile(inStream, filename, FarmDocFiles.getFileDirPath() + docfile.getDir())
				.longValue();
		docfile.setLen(Float.valueOf(String.valueOf(length)));
		docfile = this.farmDocfileDao.insertEntity(docfile);
		return docfile.getId();
	}

	public String getFileURL(String fileid) {
		String url = DocumentConfig.getString("config.doc.download.url") + fileid;
		return url;
	}

	@Transactional
	public FarmDocfile getFile(String fileid) {
		if (fileCatch.containsKey(fileid)) {
			log.debug("load file from catch");
			return (FarmDocfile) fileCatch.get(fileid);
		} else {
			FarmDocfile file = this.farmDocfileDao.getEntity(fileid);
			if (file == null) {
				return null;
			} else {
				file.setFile(
						new File(FarmDocFiles.getFileDirPath() + File.separator + file.getDir() + file.getFilename()));
				if (file.getLen().floatValue() == 0.0F) {
					file.setLen(Float.valueOf(String.valueOf(file.getFile().length())));
					if (file.getLen().floatValue() == 0.0F) {
						file.setLen(-1.0F);
					}

					this.farmDocfileDao.editEntity(file);
				}

				if (fileCatch.size() < 10000) {
					fileCatch.put(fileid, file);
				}

				return file;
			}
		}
	}

	public File getNoneImg() {
		String imgpath = FarmParameterService.getInstance().getParameter("config.doc.none.img.path");
		return new File(FarmParameterService.getInstance().getParameter("farm.constant.webroot.path") + File.separator
				+ imgpath.replaceAll("\\\\", File.separator).replaceAll("//", File.separator));
	}

	@Transactional
	public void submitFile(String fileId, String note) {
		if (fileId != null) {
			if (!fileId.isEmpty()) {
				FarmDocfile file = this.farmDocfileDao.getEntity(fileId);
				file.setPcontent(note);
				file.setPstate("1");
				file.setEtime(TimeTool.getTimeDate14());
				this.farmDocfileDao.editEntity(file);
			}
		}
	}

	@Transactional
	public void cancelFile(String fileId) {
		if (fileId != null) {
			FarmDocfile file = this.farmDocfileDao.getEntity(fileId);
			if (file != null) {
				file.setPstate("0");
				this.farmDocfileDao.editEntity(file);
			}
		}
	}

	@Transactional
	public void delFile(String fileId, LoginUser user) {
		if (fileId != null) {
			FarmDocfile docfile = this.farmDocfileDao.getEntity(fileId);
			if (docfile != null) {
				File file = this.getFile(fileId).getFile();
				this.farmDocfileDao.deleteEntity(docfile);

				try {
					if (file.exists()) {
						if (file.delete()) {
							log.info("删除成功！");
						} else {
							log.error("文件删除失败,未能删除请手动删除！");
						}
					}
				} catch (Exception var6) {
					log.error(var6.getMessage());
				}

				fileCatch.remove(fileId);
			}
		}
	}

	@Transactional
	public FarmDocfile openFile(String exname, String content, LoginUser user) {
		FILE_TYPE type = FILE_TYPE.OHTER;
		String filename = UUID.randomUUID().toString().replaceAll("-", "") + exname + ".file";
		FarmDocfile docfile = new FarmDocfile(FarmDocFiles.generateDir(),
				UUID.randomUUID().toString().replaceAll("-", ""), type.getValue(), filename, filename,
				TimeTool.getTimeDate14(), TimeTool.getTimeDate14(), user.getName(), user.getId(), user.getName(),
				user.getId(), "0", content, exname, 0.0F);
		File file = new File(FarmDocFiles.getFileDirPath() + docfile.getDir() + File.separator + docfile.getFilename());

		try {
			if (!file.createNewFile()) {
				throw new RuntimeException("文件创建失败!");
			}
		} catch (IOException var9) {
			throw new RuntimeException(var9);
		}

		docfile = this.farmDocfileDao.insertEntity(docfile);
		docfile.setFile(file);
		return docfile;
	}

	@Transactional
	public void addFileForDoc(String docid, String fileId, LoginUser user, String note) {
		this.farmRfDoctextfileDao.insertEntity(new FarmRfDoctextfile(docid, fileId));
		this.submitFile(fileId, note);
	}

	@Transactional
	public void delFileForDoc(String docid, String fileId, LoginUser user) {
		List<DBRule> list = new ArrayList();
		list.add(new DBRule("FILEID", fileId, "="));
		list.add(new DBRule("DOCID", docid, "="));
		this.farmRfDoctextfileDao.deleteEntitys(list);
		this.cancelFile(fileId);
	}

	@Transactional
	public List<FarmDocfile> getAllFileForDoc(String docid) {
		List<FarmDocfile> refiles = this.farmDocfileDao.getEntityByDocId(docid);
		Iterator var4 = refiles.iterator();

		while (var4.hasNext()) {
			FarmDocfile file = (FarmDocfile) var4.next();
			this.getFile(file.getId());
		}

		return refiles;
	}

	public List<FarmDocfile> getAllTypeFileForDoc(String docid, String exname) {
		List<FarmDocfile> refiles = this.farmDocfileDao.getEntityByDocId(docid);
		List<FarmDocfile> newrefiles = new ArrayList();
		Iterator var6 = refiles.iterator();

		while (var6.hasNext()) {
			FarmDocfile file = (FarmDocfile) var6.next();
			if (file.getExname().toUpperCase().equals(exname.toUpperCase())) {
				file = this.getFile(file.getId());
				newrefiles.add(file);
			}
		}

		return newrefiles;
	}

	public boolean containFileByDoc(String docid, String fileId) {
		List<FarmDocfile> list = this.farmDocfileDao.getEntityByDocId(docid);
		Iterator var5 = list.iterator();

		while (var5.hasNext()) {
			FarmDocfile node = (FarmDocfile) var5.next();
			if (node.getId().equals(fileId)) {
				return true;
			}
		}

		return false;
	}

	/** @deprecated */
	@Deprecated
	public void delAllFileForDoc(String docid, String exname, LoginUser aloneUser) {
		List<FarmDocfile> refiles = this.farmDocfileDao.getEntityByDocId(docid);
		Iterator var6 = refiles.iterator();

		while (var6.hasNext()) {
			FarmDocfile file = (FarmDocfile) var6.next();
			if (file.getExname().toUpperCase().equals(exname.toUpperCase())) {
				this.delFileForDoc(docid, file.getId(), aloneUser);
			}
		}

	}

	@Transactional
	public void delFileForDoc(String docid, LoginUser user) {
		List<FarmDocfile> files = this.getAllFileForDoc(docid);
		Iterator var5 = files.iterator();

		while (var5.hasNext()) {
			FarmDocfile file = (FarmDocfile) var5.next();
			this.delFileForDoc(docid, file.getId(), user);
		}

	}

	@Transactional
	public void updateFileText(String docid, String fileid, String text) {
		if (text != null) {
			List<DBRule> rules = new ArrayList();
			rules.add(new DBRule("FILEID", fileid, "="));
			rules.add(new DBRule("DOCID", docid, "="));
			List<Docfiletext> lists = this.docfiletextDaoImpl.selectEntitys(rules);
			if (text != null && text.length() > 60000) {
				text = text.substring(0, 60000);
			}

			String textmin = text;
			if (text != null && text.length() > 120) {
				textmin = text.substring(0, 120);
			}

			Docfiletext filetext;
			if (lists.size() > 0) {
				filetext = (Docfiletext) lists.get(0);
				filetext.setDescribes(text);
				filetext.setDescribesmin(textmin);
				this.docfiletextDaoImpl.editEntity(filetext);
			} else {
				filetext = new Docfiletext();
				filetext.setDescribes(text);
				filetext.setDocid(docid);
				filetext.setFileid(fileid);
				filetext.setDescribesmin(textmin);
				this.docfiletextDaoImpl.insertEntity(filetext);
			}

		}
	}

	@Transactional
	public Docfiletext getFiletext(String fileid) {
		List<DBRule> rules = new ArrayList();
		rules.add(new DBRule("FILEID", fileid, "="));
		List<Docfiletext> lists = this.docfiletextDaoImpl.selectEntitys(rules);
		return lists.size() > 0 ? (Docfiletext) lists.get(0) : null;
	}

	@Transactional
	public void updateFileState(String oldfileId, String newfileId, LoginUser user) {
		try {
			this.cancelFile(oldfileId);
			this.submitFile(newfileId, this.farmDocfileDao.getEntity(oldfileId).getPcontent());
			if (newfileId != null && !newfileId.equals(oldfileId)) {
				this.delFile(oldfileId, user);
			}
		} catch (Exception var5) {
			log.error(var5.getMessage());
		}

	}
}
